package com.zgc.simpleholiday.controlled;

import com.zgc.simpleholiday.model.DayStatus;
import com.zgc.simpleholiday.service.HolidayService;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

@Controller
@ResponseBody
public class HolidayControlled {

    private final HolidayService holidayService;

    public HolidayControlled(HolidayService holidayService) {
        this.holidayService = holidayService;
    }

    @GetMapping("/isHoliday")
    public Boolean isHoliday() {
        return nowStatus() == DayStatus.HOLIDAY || nowStatus() == DayStatus.WEEKEND;
    }

    @GetMapping("/")
    public DayStatus nowStatus() {
        return isHolidayByDate(LocalDate.now().toString());
    }

    @GetMapping("/{date}")
    public DayStatus isHolidayByDate(@PathVariable("date") String date) {
        Assert.notNull(isLegalDate(date), "日期格式错误，请检查日期格式是否为yyyy-MM-dd格式， 例如：2021-01-01"); // 校验date的格式为"yyyy-MM-dd"
        String[] dateSplit = date.split("-");
        return holidayService.getHoliday(dateSplit[0], dateSplit[1], dateSplit[2]);
    }

    private static Date isLegalDate(String sDate) {
        int legalLen = 10;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return null;
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date))? date: null;
        } catch (Exception e) {
            throw new RuntimeException("日期格式错误，请检查日期格式是否为yyyy-MM-dd格式以及是否是正常的日期， 例如：2021-01-01");
        }
    }



}
